#!/usr/bin/python
'''
from aspn python cookbook
'''

from __future__ import nested_scopes
import sys
import re

def multiple_replace(adict, text):
    #regex = re.compile("|".join(map(re.escape, adict.keys())))
    regex = re.compile("|".join(adict.keys()))
    return regex.sub(lambda match: adict[match.group(0)], text)

try: dict
except: from UserDict import UserDict as dict

class Xlator(dict):
    """ All-in-one multiple-string-substitution class """
    def _make_regex(self):
        """ Build re object based on the keys of the current dictionary """
        #return re.compile("|".join(map(re.escape, self.keys())))
        return re.compile("|".join(self.keys()))

    def __call__(self, match):
        """ Handler invoded for each regex match """
        return self[match.group(0)]

    def xlat(self, text):
        """ Translate text, returns the modified text. """
        return self._make_regex().sub(self, text)

class StaticXlator(dict):
    """ All-in-one multiple-string-substitution class """
    def __init__(self, adict):
        """ Build re object based on the keys of the current dictionary """
        dict.__init__(self, adict)
        #pattern = re.compile("|".join(map(re.escape, self.keys())))
        self.pattern = re.compile("|".join(self.keys()))

    def __call__(self, match):
        """ Handler invoded for each regex match """
        return self[match.group(0)]

    def xlat(self, text):
        """ Translate text, returns the modified text. """
        return self.pattern.sub(self, text)

def main():
    print 'test: multiple_replace(dict, text)'
    text = 'Larry Wall is the creator of Perl'
    d = {
        'Larry Wall'    : 'Guido van Rossum',
        'creator'       : 'Benevolent Dictator for Life',
        'Perl'          : 'Python',
    }

    print multiple_replace(d, text)

    print 'test: class Xlator(dict)' 
    xl = Xlator(d)
    print xl.xlat(text)

    print 'test: class StaticXlator(dict)' 
    sxl = StaticXlator(d)
    print sxl.xlat(text)

def about():
    from os.path import basename
    import sys
    (appName, appExtention) = basename(sys.argv[0]).split('.')
    exec 'import %s'%(appName)
    exec 'print %s.__doc__' %(appName)

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        if sys.argv[1] in '-a --about'.split():
            about()
            sys.exit()
    main()

